import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import {
  CreateTodoTaskDto,
  DeleteTodoTaskDto,
  FindManyTodoTaskDto,
  UpdateTodoTaskDto,
} from './dto/todo-task.dto';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class TodoTaskService {
  constructor(private readonly prismaService: PrismaService) {}

  async create(cd: CreateTodoTaskDto) {
    const cdobj = await this.prismaService.todotask.findFirst({
      where: { name: cd.name },
    });
    if (cdobj) {
      throw new HttpException('已存在', HttpStatus.BAD_REQUEST);
    }
    return this.prismaService.todotask.create({
      data: {
        ...cd,
        status: 0,
      },
    });
  }

  delete(dd: DeleteTodoTaskDto) {
    try {
      return this.prismaService.todotask.delete({ where: { id: dd.id } });
    } catch (error) {
      throw new HttpException('删除失败', HttpStatus.BAD_REQUEST);
    }
  }

  async update(ud: UpdateTodoTaskDto) {
    const upobj = await this.prismaService.todotask.findFirst({
      where: { name: ud.name, NOT: { id: ud.id } },
    });
    if (upobj) {
      throw new HttpException('已存在', HttpStatus.BAD_REQUEST);
    }
    try {
      const { id, ...rest } = ud;
      return this.prismaService.todotask.update({
        where: { id },
        data: {
          ...rest,
        },
      });
    } catch (error) {
      throw new HttpException('编辑失败', HttpStatus.BAD_REQUEST);
    }
  }

  async findMany(fmd: FindManyTodoTaskDto) {
    try {
      const res = await this.prismaService.todotask.findMany({});
      return res;
    } catch (error) {
      throw new HttpException('获取列表失败', HttpStatus.BAD_REQUEST);
    }
  }
}
